package com.bv.hr.system.aspect;

import com.alibaba.fastjson.JSONObject;
import com.bv.hr.system.entity.Log;
import com.bv.hr.system.service.LogService;
import com.bv.hr.system.util.HttpUtils;
import com.bv.hr.system.util.IpUtils;
import com.bv.hr.system.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;

/**
 * @author CYT7
 * @version 1.0
 * @fileName SysLogAspect
 * @time 12月 20,2021
 * @describe 系统日志，切面处理类，记录日志
 */
@Aspect
@Component
@RequiredArgsConstructor
public class SysLogAspect {
    private final LogService logService;

    @Pointcut("execution(* com.bv.hr.*.service.*.*(..))")
    public void logPointCut(){}
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point)throws Throwable{
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长（毫秒）
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        saveSysLog(point, time);
        return result;
    }
    private void saveSysLog(ProceedingJoinPoint joinPoint, long time){
        String username = SecurityUtils.getUsername();
        if (joinPoint.getTarget() instanceof LogService){
            return;
        }
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Log log = new Log();
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.setMethod(className + "." + methodName + "()");
        //请求的参数
        Object[] args = joinPoint.getArgs();
        try {
            String params = JSONObject.toJSONString(args[0]);
            int paramsLength = 200;
            if (params.length()> paramsLength){
                params = params.substring(0, 200) + "...";
            }
            log.setParams(params);
        }catch (Exception e){
            //ignore
        }
        //获取request
        HttpServletRequest request = HttpUtils.getHttpServletRequest();
        //设置ip地址
        log.setIp(IpUtils.getIpAddr(request));
        //用户名
        log.setUserName(username);
        //执行时长（毫秒）
        log.setTime(time);
        //保存系统日志
        logService.save(log);
    }
}
